package com.purchasing.system.controller;

import com.purchasing.system.model.Permission;
import com.purchasing.system.repository.PermissionRepository;
import com.purchasing.system.security.services.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/permissions")
public class PermissionController {

    @Autowired
    private PermissionRepository permissionRepository;

    // 获取所有权限
    @GetMapping
//    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ResponseEntity<List<Permission>> getAllPermissions() {
        List<Permission> permissions = permissionRepository.findAll();
        return ResponseEntity.ok(permissions);
    }

    // 创建新权限
    @PostMapping
//    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ResponseEntity<Permission> createPermission(@RequestBody Permission permission) {
        try {
            // 检查权限名称是否已存在
            if (permissionRepository.existsByName(permission.getName())) {
                return new ResponseEntity<>(null, HttpStatus.CONFLICT);
            }

            Permission savedPermission = permissionRepository.save(permission);
            return new ResponseEntity<>(savedPermission, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/my")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<List<String>> getCurrentUserPermissions() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            if (authentication == null || !(authentication.getPrincipal() instanceof UserDetailsImpl)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }

            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();

            // 获取用户所有权限（扁平化处理）
            List<String> permissions = userDetails.getUser().getRoles().stream()
                    .flatMap(role -> role.getPermissions().stream())
                    .map(Permission::getName)
                    .distinct() // 去重
                    .collect(Collectors.toList());

            return ResponseEntity.ok(permissions);

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // 根据ID获取权限
    @GetMapping("/{id}")
//    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ResponseEntity<Permission> getPermissionById(@PathVariable Long id) {
        Optional<Permission> permissionData = permissionRepository.findById(id);
        return permissionData.map(permission -> new ResponseEntity<>(permission, HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    // 更新权限
    @PutMapping("/{id}")
//    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ResponseEntity<Permission> updatePermission(@PathVariable Long id, @RequestBody Permission permission) {
        Optional<Permission> permissionData = permissionRepository.findById(id);

        if (permissionData.isPresent()) {
            Permission existingPermission = permissionData.get();

            // 检查新名称是否与其他权限冲突
            if (!existingPermission.getName().equals(permission.getName()) &&
                    permissionRepository.existsByName(permission.getName())) {
                return new ResponseEntity<>(null, HttpStatus.CONFLICT);
            }

            existingPermission.setName(permission.getName());
            existingPermission.setDescription(permission.getDescription());
            return new ResponseEntity<>(permissionRepository.save(existingPermission), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    // 删除权限
    @DeleteMapping("/{id}")
//    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ResponseEntity<HttpStatus> deletePermission(@PathVariable Long id) {
        try {
            // 检查权限是否被角色使用
            if (permissionRepository.isPermissionAssignedToAnyRole(id)) {
                return new ResponseEntity<>(HttpStatus.CONFLICT);
            }

            permissionRepository.deleteById(id);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


}

